/* eslint-disable */
<template>
  <div class="course-detail">
    <!-- 课程头部信息 -->
    <div class="course-header">
      <div class="course-info">
        <h2>{{ course.name }}</h2>
        <p>{{ course.className }} | {{ course.time }}</p>
      </div>
      <div class="course-stats">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="stat-card">
              <div class="stat-value">{{ course.studentCount }}</div>
              <div class="stat-label">学生人数</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-card">
              <div class="stat-value">{{ course.homeworkCount }}</div>
              <div class="stat-label">发布作业</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 功能导航 -->
    <div class="nav-section">
      <el-menu :default-active="activeTab" mode="horizontal" @select="handleSelect">
        <el-menu-item index="info">课程信息</el-menu-item>
        <el-menu-item index="students">学生管理</el-menu-item>
        <el-menu-item index="homework">作业管理</el-menu-item>
        <el-menu-item index="announcement">公告管理</el-menu-item>
        <el-menu-item index="quiz">随堂测试</el-menu-item>
      </el-menu>
    </div>

    <!-- 内容区域 -->
    <div class="content-section">
      <!-- 课程信息 -->
      <div v-if="activeTab === 'info'" class="info-content">
        <el-form :model="course" label-width="100px">
          <el-form-item label="课程名称">
            <span>{{ course.name }}</span>
          </el-form-item>
          <el-form-item label="班级">
            <span>{{ course.className }}</span>
          </el-form-item>
          <el-form-item label="学期">
            <span>{{ course.time }}</span>
          </el-form-item>
          <el-form-item label="课程描述">
            <span>{{ course.description }}</span>
          </el-form-item>
        </el-form>
      </div>

      <!-- 学生管理 -->
      <div v-if="activeTab === 'students'" class="students-content">
        <div class="table-header">
          <el-input
            v-model="studentSearch"
            placeholder="搜索学生"
            style="width: 200px"
            @input="handleStudentSearch">
            <i slot="prefix" class="el-icon-search"></i>
          </el-input>
        </div>
        
        <el-table :data="filteredStudents" style="width: 100%" v-loading="studentsLoading">
          <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="className" label="班级"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="viewStudentDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 作业管理 -->
      <div v-if="activeTab === 'homework'" class="homework-content">
        <div class="table-header">
          <el-button type="primary" @click="handleAddHomework">发布作业</el-button>
        </div>

        <el-table :data="homeworkList" style="width: 100%" v-loading="homeworkLoading">
          <el-table-column prop="title" label="作业标题"></el-table-column>
          <el-table-column prop="deadline" label="截止时间" width="180"></el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button 
                size="mini" 
                type="primary" 
                @click="handleGradeHomework(scope.row)">
                批改
              </el-button>
              <el-button 
                size="mini" 
                @click="viewHomeworkDetail(scope.row)">
                详情
              </el-button>
              <el-button 
                size="mini" 
                type="danger" 
                @click="handleDeleteHomework(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 公告管理 -->
      <div v-if="activeTab === 'announcement'" class="announcement-content">
        <div class="table-header">
          <el-button type="primary" @click="handleAddAnnouncement">发布公告</el-button>
        </div>

        <el-table :data="announcements" style="width: 100%" v-loading="announcementsLoading">
          <el-table-column prop="title" label="标题"></el-table-column>
          <el-table-column prop="content" label="内容" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="createTime" label="发布时间" width="180"></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" @click="editAnnouncement(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteAnnouncement(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 随堂测试 -->
      <div v-if="activeTab === 'quiz'" class="quiz-content">
        <div class="table-header">
          <el-button type="primary" @click="handleCreateQuiz">创建随堂测试</el-button>
        </div>

        <el-table :data="quizList" style="width: 100%" v-loading="quizLoading">
          <el-table-column prop="title" label="测试标题"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getQuizStatusType(scope.row.status)">{{ getQuizStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleViewQuizDetail(scope.row)">查看详情</el-button>
              <el-button 
                size="mini" 
                :type="scope.row.status === 0 ? 'success' : 'warning'"
                @click="handleQuizStatus(scope.row)">
                {{ scope.row.status === 0 ? '开始测试' : scope.row.status === 1 ? '结束测试' : '已结束' }}
              </el-button>
              <el-button 
                size="mini" 
                type="danger" 
                @click="handleDeleteQuiz(scope.row)"
                :disabled="scope.row.status === 1">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 发布作业对话框 -->
    <el-dialog :title="homeworkDialog.title" :visible.sync="homeworkDialog.visible" width="50%">
      <el-form :model="homeworkForm" :rules="homeworkRules" ref="homeworkForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="homeworkForm.title"></el-input>
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker
            v-model="homeworkForm.deadline"
            type="datetime"
            placeholder="选择截止时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作业要求" prop="description">
          <el-input type="textarea" v-model="homeworkForm.description" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="homeworkForm.fileList"
            :on-change="handleFileChange">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">支持任意格式文件，单个文件不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="homeworkDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitHomework">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批改作业对话框 -->
    <el-dialog title="批改作业" :visible.sync="gradeDialog.visible" width="85%" top="5vh">
      <!-- 作业基本信息 -->
      <div v-if="gradeDialog.currentHomework" class="homework-header">
        <h3>{{ gradeDialog.currentHomework.title }}</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">截止时间：</span>
              <span>{{ gradeDialog.currentHomework.deadline }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">提交情况：</span>
              <span>
                <el-tag type="success">{{ submissionList.length }}</el-tag> / {{ course.studentCount }}
              </span>
            </div>
          </el-col>
        </el-row>
        <div class="info-item" v-if="gradeDialog.currentHomework.description">
          <span class="info-label">作业描述：</span>
          <p class="description-text">{{ gradeDialog.currentHomework.description }}</p>
        </div>
        <div class="info-item" v-if="gradeDialog.currentHomework.resourceUrl">
          <span class="info-label">附件：</span>
          <el-button type="text" @click="downloadHomeworkResource(gradeDialog.currentHomework.resourceUrl)">
            {{ getOriginalFileName(gradeDialog.currentHomework.resourceUrl) }}
          </el-button>
        </div>
        <el-divider></el-divider>
      </div>
      
      <!-- 批改操作栏 -->
      <div class="grade-toolbar">
        <div>
          <span class="filter-label">状态筛选：</span>
            <el-radio-group v-model="gradeFilter" size="mini" @change="filterSubmissions">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="graded">已批改</el-radio-button>
              <el-radio-button label="ungraded">未批改</el-radio-button>
            <el-radio-button label="overdue">超期提交</el-radio-button>
            </el-radio-group>
        </div>
      </div>
      
      <div class="grade-content">
        <el-table 
          :data="filteredSubmissionList" 
          style="width: 100%" 
          v-loading="submissionsLoading"
          @row-click="viewSubmissionDetail">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="120" sortable></el-table-column>
          <el-table-column prop="studentName" label="姓名" width="100" sortable></el-table-column>
          <el-table-column prop="submitTime" label="提交时间" width="160" sortable></el-table-column>
          <el-table-column label="作业文件" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click.stop="downloadSubmission(scope.row)">
                {{ scope.row.fileName }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="成绩" width="150">
            <template slot-scope="scope">
              <el-input-number 
                v-model="scope.row.score" 
                :min="0" 
                :max="100"
                size="mini"
                @click.native.stop>
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="评语">
            <template slot-scope="scope">
              <el-input 
                v-model="scope.row.comment"
                size="mini"
                placeholder="请输入评语"
                @click.native.stop>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template slot-scope="scope">
              <div>
              <el-tag 
                :type="scope.row.score > 0 ? 'success' : 'info'" 
                size="mini">
                {{ scope.row.score > 0 ? '已批改' : '未批改' }}
              </el-tag>
                <el-tag 
                  v-if="scope.row.isOverdue" 
                  type="danger" 
                  size="mini" 
                  style="margin-top: 5px; display: block; font-weight: bold;">
                  超期提交
                </el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 无数据提示 -->
        <div v-if="filteredSubmissionList.length === 0 && !submissionsLoading" class="no-data">
          <i class="el-icon-document"></i>
          <p>暂无提交记录</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gradeDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitGrades" :disabled="submissionList.length === 0">保存评分</el-button>
      </span>
    </el-dialog>

    <!-- 发布公告对话框 -->
    <el-dialog :title="announcementDialog.title" :visible.sync="announcementDialog.visible" width="50%">
      <el-form :model="announcementForm" :rules="announcementRules" ref="announcementForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="announcementForm.content" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="announcementDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitAnnouncement">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 作业详情对话框 -->
    <el-dialog title="作业详情" :visible.sync="homeworkDetailDialog.visible" width="50%">
      <div v-if="currentHomework" class="homework-detail">
        <h3>{{ currentHomework.title }}</h3>
        <el-divider></el-divider>
        <div class="detail-item">
          <span class="label">截止时间：</span>
          <span>{{ currentHomework.deadline }}</span>
        </div>
        <div class="detail-item">
          <span class="label">描述：</span>
          <span>{{ currentHomework.description || '无' }}</span>
        </div>
        <div v-if="currentHomework.resourceUrl" class="detail-item">
          <span class="label">附件：</span>
          <span 
            class="file-link" 
            @click="downloadHomeworkResource(currentHomework.resourceUrl)">
            {{ getOriginalFileName(currentHomework.resourceUrl) }}
          </span>
        </div>
      </div>
    </el-dialog>

    <!-- 提交详情对话框 -->
    <el-dialog title="提交详情" :visible.sync="submissionDetailDialog.visible" width="60%">
      <div v-if="currentSubmission" class="submission-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生姓名">{{ currentSubmission.studentName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ currentSubmission.studentId }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentSubmission.submitTime }}
            <el-tag v-if="currentSubmission.isOverdue" type="danger" size="mini" style="margin-left: 10px">超期提交</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件">
            <el-button type="text" @click="downloadSubmission(currentSubmission)">
              {{ currentSubmission.fileName }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="成绩" :span="2">
            <el-input-number 
              v-model="currentSubmission.score" 
              :min="0" 
              :max="100"
              size="small">
            </el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="评语" :span="2">
            <el-input 
              type="textarea" 
              v-model="currentSubmission.comment"
              :rows="3"
              placeholder="请输入评语">
            </el-input>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submissionDetailDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="saveCurrentSubmission">保存</el-button>
      </span>
    </el-dialog>

        <!-- 学生详情对话框 -->
    <el-dialog title="学生详情" :visible.sync="studentDetailDialog.visible" width="60%">
      <div class="profile-content" v-loading="studentDetailDialog.loading">
        <h2 class="profile-title">学生个人信息</h2>
        
        <!-- 学生详情表单 -->
        <el-form label-width="100px" v-if="studentDetailDialog.studentInfo">
          <!-- 头像显示区域 -->
          <el-form-item label="头像">
            <div class="avatar-container">
              <div class="avatar-wrapper">
                <img 
                  v-if="studentDetailDialog.studentInfo.avatarUrl && studentDetailDialog.studentInfo.avatarUrl.startsWith('http')" 
                  :src="studentDetailDialog.studentInfo.avatarUrl" 
                  class="avatar-image" 
                  alt="头像" 
                />
                <img 
                  v-else-if="studentDetailDialog.studentInfo.avatarUrl" 
                  :src="`https://stu-work.oss-cn-shenzhen.aliyuncs.com/${studentDetailDialog.studentInfo.avatarUrl}`" 
                  class="avatar-image" 
                  alt="头像" 
                />
                <img 
                  v-else 
                  src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" 
                  class="avatar-image" 
                  alt="默认头像" 
                />
  </div>
            </div>
          </el-form-item>
          
          <!-- 学号 -->
          <el-form-item label="学号">
            <el-input v-model="studentDetailDialog.studentInfo.studentId" disabled></el-input>
          </el-form-item>
          
          <!-- 姓名 -->
          <el-form-item label="姓名">
            <el-input v-model="studentDetailDialog.studentInfo.name" disabled></el-input>
          </el-form-item>
          
          <!-- 性别 -->
          <el-form-item label="性别">
            <el-input v-model="studentDetailDialog.studentInfo.gender" disabled></el-input>
          </el-form-item>
          
          <!-- 班级 -->
          <el-form-item label="班级">
            <el-input v-model="studentDetailDialog.studentInfo.className" disabled></el-input>
          </el-form-item>
          
          <!-- 院系 -->
          <el-form-item label="院系">
            <el-input :value="studentDetailDialog.studentInfo.deptName || studentDetailDialog.studentInfo.deptNumber" disabled></el-input>
          </el-form-item>
          
          <!-- 手机号 -->
          <el-form-item label="手机号">
            <el-input v-model="studentDetailDialog.studentInfo.phone" disabled></el-input>
          </el-form-item>
          
          <!-- 邮箱 -->
          <el-form-item label="邮箱">
            <el-input v-model="studentDetailDialog.studentInfo.email" disabled></el-input>
          </el-form-item>
          
          <!-- 入学年份 -->
          <el-form-item label="入学年份" v-if="studentDetailDialog.studentInfo.year">
            <el-input v-model="studentDetailDialog.studentInfo.year" disabled></el-input>
          </el-form-item>
        </el-form>
        
        <!-- 课程表现信息 -->
        <div v-if="studentDetailDialog.courseStats" style="margin-top: 20px">
          <h2 class="profile-title">课程表现</h2>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-title">作业提交率</div>
                <el-progress type="circle" :percentage="studentDetailDialog.courseStats.submissionRate || 0"></el-progress>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-title">平均成绩</div>
                <div class="stat-value">{{ studentDetailDialog.courseStats.averageScore || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-item">
                <div class="stat-title">未提交作业</div>
                <div class="stat-value">{{ studentDetailDialog.courseStats.missedAssignments || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <!-- 作业提交记录 -->
        <div v-if="studentDetailDialog.submissions && studentDetailDialog.submissions.length > 0" style="margin-top: 20px">
          <h2 class="profile-title">作业提交记录</h2>
          <el-table :data="studentDetailDialog.submissions" style="width: 100%">
            <el-table-column prop="assignmentTitle" label="作业标题"></el-table-column>
            <el-table-column prop="submitTime" label="提交时间" width="180"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '已批改' ? 'success' : 'info'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="成绩" width="80"></el-table-column>
          </el-table>
        </div>
        
        <!-- 无提交记录提示 -->
        <div v-else-if="studentDetailDialog.submissions && studentDetailDialog.submissions.length === 0 && !studentDetailDialog.loading" style="margin-top: 20px">
          <h2 class="profile-title">作业提交记录</h2>
          <div class="no-data">
            <i class="el-icon-document"></i>
            <p>没有提交作业记录</p>
          </div>
        </div>
        
        <!-- 无数据提示 -->
        <div v-if="!studentDetailDialog.studentInfo && !studentDetailDialog.loading" class="no-data">
          <i class="el-icon-warning"></i>
          <p>未找到学生信息</p>
        </div>
      </div>
    </el-dialog>

    <!-- 创建随堂测试对话框 -->
    <el-dialog :title="quizDialog.title" :visible.sync="quizDialog.visible" width="60%" :close-on-click-modal="false">
      <div class="quiz-form">
        <div class="form-item">
          <label class="form-label required">测试标题</label>
          <el-input v-model="quizForm.title" placeholder="请输入随堂测试标题"></el-input>
        </div>
        <div class="form-item">
          <label class="form-label">测试说明</label>
          <el-input type="textarea" v-model="quizForm.description" :rows="3" placeholder="请输入测试说明（选填）"></el-input>
        </div>
        
        <!-- 已添加的题目列表 -->
        <el-divider content-position="left">已添加题目({{ quizForm.questions.length }})</el-divider>
        <el-collapse v-if="quizForm.questions.length > 0">
          <el-collapse-item v-for="(question, index) in quizForm.questions" :key="index" :title="`题目${index + 1}：${question.content.substring(0, 20)}${question.content.length > 20 ? '...' : ''}`">
            <div class="question-item">
              <div class="question-content">{{ question.content }}</div>
              <div class="question-options">
                <p v-for="(option, optIndex) in question.options" :key="optIndex" :class="{ 'correct-option': optIndex === Number(question.answer) }">
                  <span class="option-label">{{ ['A', 'B', 'C', 'D'][optIndex] }}. </span>
                  {{ option }}
                </p>
              </div>
              <div class="question-actions">
                <el-button size="mini" type="danger" @click.prevent="removeQuestion(index)">删除题目</el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-else description="暂无题目，请添加题目"></el-empty>
        
        <!-- 添加新题目部分 -->
        <el-divider content-position="left">添加新题目</el-divider>
        <div class="new-question-form">
          <div class="form-item">
            <label class="form-label required">题目内容</label>
            <el-input type="textarea" v-model="currentQuestion.content" :rows="2" placeholder="请输入题目内容"></el-input>
          </div>
          <!-- 选项 -->
          <div class="form-item" v-for="(option, index) in currentQuestion.options" :key="index">
            <label class="form-label required">选项{{ ['A', 'B', 'C', 'D'][index] }}</label>
            <el-input v-model="currentQuestion.options[index]" :placeholder="`请输入选项${['A', 'B', 'C', 'D'][index]}`"></el-input>
          </div>
          <!-- 正确答案 -->
          <div class="form-item">
            <label class="form-label required">正确答案</label>
            <el-radio-group v-model="currentQuestion.answer">
              <el-radio :label="0">A</el-radio>
              <el-radio :label="1">B</el-radio>
              <el-radio :label="2">C</el-radio>
              <el-radio :label="3">D</el-radio>
            </el-radio-group>
          </div>
          
          <el-button type="primary" @click="addQuestion">添加题目</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="quizDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitQuiz" :disabled="quizForm.questions.length === 0">创建测试</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseDetail, getStudentsByClassId, getAnnouncementsByCourseAndClass, addCourseAnnouncement, updateCourseAnnouncement, deleteCourseAnnouncement, getCourseAssignments, addAssignment, deleteAssignment, getSubmissionsByAssignmentId, gradeSubmission, uploadAssignmentResource, getStudentById, getAssignmentDetail } from '@/api/teacher'
/* eslint-disable no-unused-vars */
import { getSubmissionsByStudentId } from '@/api/student'
/* eslint-enable no-unused-vars */
import { getCourseQuizList, createQuiz, startQuiz, endQuiz, deleteQuiz } from '@/api/quiz'

export default {
  name: 'TeacherCourseDetail',
  data() {
    return {
      activeTab: 'info',
      loading: false,
      studentsLoading: false,
      studentSearch: '',
      course: {
        id: '',
        name: '',
        className: '',
        time: '',
        schedule: '',
        location: '',
        description: '',
        studentCount: 0,
        homeworkCount: 0,
        pendingHomework: 0
      },
      students: [],
      homeworkList: [],
      homeworkLoading: false,
      announcements: [],
      announcementsLoading: false,
      homeworkDialog: {
        visible: false,
        title: '发布作业'
      },
      homeworkForm: {
        title: '',
        deadline: '',
        description: '',
        fileList: []
      },
      homeworkRules: {
        title: [
          { required: true, message: '请输入作业标题', trigger: 'blur' }
        ],
        deadline: [
          { required: true, message: '请选择截止时间', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入作业要求', trigger: 'blur' }
        ]
      },
      gradeDialog: {
        visible: false,
        currentHomework: null
      },
      submissionList: [],
      filteredSubmissionList: [],
      submissionsLoading: false,
      gradeFilter: 'all',
      submissionDetailDialog: {
        visible: false
      },
      currentSubmission: null,
      batchScoreDialog: {
        visible: false,
        score: 0,
        comment: ''
      },
      announcementDialog: {
        visible: false,
        title: '发布公告'
      },
      announcementForm: {
        title: '',
        content: '',
        courseId: '',
        classId: '',
        teacherId: ''
      },
      announcementRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      },
      homeworkDetailDialog: {
        visible: false,
        currentHomework: null
      },
      currentHomework: null,
      studentDetailDialog: {
        visible: false,
        loading: false,
        studentInfo: null
      },
      // 随堂测试相关数据
      quizList: [],
      quizLoading: false,
      quizDialog: {
        visible: false,
        title: '创建随堂测试'
      },
      quizForm: {
        title: '',
        description: '',
        questions: []
      },
      quizRules: {
        title: [
          { required: true, message: '请输入测试标题', trigger: 'blur' }
        ]
      },
      currentQuestion: {
        content: '',
        options: ['', '', '', ''],
        answer: 0
      }
    }
  },
  computed: {
    filteredStudents() {
      if (!this.studentSearch) {
        return this.students
      }
      const search = this.studentSearch.toLowerCase()
      return this.students.filter(student => 
        (student.studentId && student.studentId.toLowerCase().includes(search)) ||
        (student.name && student.name.toLowerCase().includes(search)) ||
        (student.className && student.className.toLowerCase().includes(search))
      )
    }
  },
  created() {
    // 检查教师ID是否存在
    const teacherId = this.getCurrentTeacherId()
    if (!teacherId) {
      this.$message.warning('未检测到教师ID，可能需要重新登录')
    }
    
    // 从路由参数获取课程ID和班级ID
    const courseId = this.$route.params.id
    const classId = this.$route.query.classId
    
    if (courseId && classId) {
      this.loadCourseDetail(courseId, classId)
      
      // 初始加载学生数据（如果默认标签是学生管理）
      if (this.activeTab === 'students') {
        this.loadStudents(classId)
      }
      
      // 初始加载作业数据（如果默认标签是作业管理）
      if (this.activeTab === 'homework') {
        this.loadHomeworkList()
      }
      
      // 初始加载公告数据（如果默认标签是公告管理）
      if (this.activeTab === 'announcement') {
        this.loadAnnouncements()
      }
      
      // 当切换到随堂测试标签页时，加载测试列表
      if (this.activeTab === 'quiz' && this.quizList.length === 0) {
        this.loadQuizList()
      }
    } else {
      this.$message.error('缺少课程ID或班级ID参数')
    }
  },
  methods: {
    // 获取当前登录教师ID
    getCurrentTeacherId() {
      try {
        const userInfo = localStorage.getItem('userInfo')
        if (!userInfo) {
          console.error('未找到用户信息')
          return ''
        }
        
        const parsedUserInfo = JSON.parse(userInfo)
        // 教师ID可能存储在userId或teacherId字段中，需要根据实际情况调整
        return parsedUserInfo.teacherId || parsedUserInfo.userId || ''
      } catch (error) {
        console.error('解析用户信息出错:', error)
        return ''
      }
    },
    
    // 加载课程详情
    loadCourseDetail(courseId, classId) {
      this.loading = true
      getCourseDetail(courseId, classId)
        .then(response => {
          if (response.code === 200) {
            this.course = response.data
          } else {
            this.$message.error(response.msg || '获取课程详情失败')
          }
        })
        .catch(error => {
          console.error('获取课程详情错误:', error)
          this.$message.error('获取课程详情异常，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 加载班级学生列表
    loadStudents(classId) {
      if (!classId) {
        classId = this.$route.query.classId
      }
      
      if (!classId) {
        this.$message.error('缺少班级ID参数')
        return
      }
      
      this.studentsLoading = true
      getStudentsByClassId(classId)
        .then(response => {
          if (response.code === 200) {
            this.students = response.data
          } else {
            this.$message.error(response.msg || '获取学生列表失败')
          }
        })
        .catch(error => {
          console.error('获取学生列表错误:', error)
          this.$message.error('获取学生列表异常，请稍后重试')
        })
        .finally(() => {
          this.studentsLoading = false
        })
    },
    
    handleSelect(key) {
      this.activeTab = key
      
      // 当切换到学生管理标签页时，加载学生数据
      if (key === 'students' && this.students.length === 0) {
        this.loadStudents()
      }
      
      // 当切换到作业管理标签页时，加载作业数据
      if (key === 'homework' && this.homeworkList.length === 0) {
        this.loadHomeworkList()
      }
      
      // 当切换到公告管理标签页时，加载公告数据
      if (key === 'announcement' && this.announcements.length === 0) {
        this.loadAnnouncements()
      }
      
      // 当切换到随堂测试标签页时，加载测试列表
      if (key === 'quiz' && this.quizList.length === 0) {
        this.loadQuizList()
      }
    },
    
    handleStudentSearch() {
      // 实时搜索，不需要额外处理，computed属性会自动过滤
    },
    
    viewStudentDetail(student) {
      this.studentDetailDialog = {
        visible: true,
        loading: true,
        studentInfo: student, // 先用列表中的基本信息
        courseStats: null,
        submissions: []
      }
      
      const courseId = this.$route.params.id
      const classId = parseInt(this.$route.query.classId)
      
      // 首先获取课程的所有作业，用于统计数据
      getCourseAssignments(courseId, classId)
        .then(assignmentsResponse => {
          const allAssignments = (assignmentsResponse.code === 200 && assignmentsResponse.data) 
            ? assignmentsResponse.data 
            : []
          
          // 获取学生详细信息
          return getStudentById(student.studentId)
            .then(response => {
              if (response.code === 200 && response.data) {
                // 更新学生详细信息
                this.studentDetailDialog.studentInfo = response.data
                
                // 获取学生所有作业提交记录
                return getSubmissionsByStudentId(student.studentId)
                  .then(submissionsResponse => {
                    if (submissionsResponse.code === 200 && submissionsResponse.data) {
                      // 筛选出当前课程的提交记录
                      const currentCourseSubmissions = submissionsResponse.data.filter(submission => {
                        // 根据作业关联的课程ID进行筛选
                        return submission.assignment && submission.assignment.courseId === courseId
                      })
                      
                      // 计算课堂表现统计数据
                      this.studentDetailDialog.courseStats = this.calculateCourseStats(allAssignments, currentCourseSubmissions)
                      
                      // 格式化提交记录数据
                      const formattedSubmissions = currentCourseSubmissions.map(submission => {
                        const isGraded = submission.score > 0
                        return {
                          assignmentTitle: submission.assignment ? submission.assignment.title : '未知作业',
                          submitTime: this.formatDate(submission.createTime || submission.submitTime),
                          status: isGraded ? '已批改' : '待批改',
                          score: isGraded ? submission.score : 0
                        }
                      })
                      
                      this.studentDetailDialog.submissions = formattedSubmissions
                      
                      if (formattedSubmissions.length === 0) {
                        console.log('当前课程没有找到该学生的提交记录')
                      }
                    } else {
                      console.error('获取学生提交记录失败:', submissionsResponse.message)
                      this.$message.warning('获取学生提交记录失败')
                      
                      // 设置默认数据
                      this.studentDetailDialog.courseStats = {
                        submissionRate: 0,
                        averageScore: '0.0',
                        missedAssignments: allAssignments.length
                      }
                    }
                  })
                  .catch(error => {
                    console.error('获取学生提交记录出错:', error)
                    // 设置默认值
                    this.studentDetailDialog.courseStats = {
                      submissionRate: 0,
                      averageScore: '0.0',
                      missedAssignments: allAssignments.length
                    }
                  })
              } else {
                this.$message.warning('获取学生详情失败')
                return Promise.reject(new Error('获取学生详情失败'))
              }
            })
        })
        .catch(error => {
          console.error('加载课程作业或学生详情出错:', error)
          // 设置默认值
          this.studentDetailDialog.courseStats = {
            submissionRate: 0,
            averageScore: '0.0',
            missedAssignments: 0
          }
        })
        .finally(() => {
          this.studentDetailDialog.loading = false
        })
    },
    
    // 计算课程统计数据的辅助函数
    calculateCourseStats(allAssignments, studentSubmissions) {
      // 总作业数
      const totalAssignments = allAssignments.length
      if (totalAssignments === 0) {
        return {
          submissionRate: 0,
          averageScore: '0.0',
          missedAssignments: 0
        }
      }
      
      // 获取已提交的作业ID
      const submittedAssignmentIds = new Set(studentSubmissions.map(sub => 
        sub.assignmentId || (sub.assignment ? sub.assignment.assignmentId : null)
      ).filter(id => id !== null))
      const submittedCount = submittedAssignmentIds.size
      
      // 已批改的作业
      const gradedSubmissions = studentSubmissions.filter(sub => sub.score > 0)
      
      // 计算平均分
      let averageScore = '0.0'
      if (gradedSubmissions.length > 0) {
        const totalScore = gradedSubmissions.reduce((sum, sub) => sum + (parseFloat(sub.score) || 0), 0)
        averageScore = (totalScore / gradedSubmissions.length).toFixed(1)
      }
      
      // 计算提交率
      const submissionRate = Math.round((submittedCount / totalAssignments) * 100)
      
      // 未提交作业数
      const missedAssignments = totalAssignments - submittedCount
      
      return {
        submissionRate,
        averageScore,
        missedAssignments,
        totalAssignments,
        gradedCount: gradedSubmissions.length
      }
    },
    handleAddHomework() {
      this.homeworkDialog.title = '发布作业'
      this.homeworkForm = {
        title: '',
        deadline: '',
        description: '',
        fileList: []
      }
      this.homeworkDialog.visible = true
    },
    handleFileChange(file, fileList) {
      this.homeworkForm.fileList = fileList
    },
    submitHomework() {
      this.$refs.homeworkForm.validate(valid => {
        if (valid) {
          const courseId = this.$route.params.id
          const classId = parseInt(this.$route.query.classId)
          const teacherId = this.getCurrentTeacherId()
          
          if (!courseId || !classId || !teacherId) {
            this.$message.error('缺少必要参数')
            return
          }
          
          // 先上传附件（如果有）
          let uploadPromise = Promise.resolve(null)
          if (this.homeworkForm.fileList.length > 0) {
            const file = this.homeworkForm.fileList[0].raw
            if (file) {
              uploadPromise = uploadAssignmentResource(file)
            }
          }
          
          // 处理上传结果，创建作业
          uploadPromise
            .then(uploadResponse => {
              let resourceUrl = null
              if (uploadResponse && uploadResponse.code === 200) {
                resourceUrl = uploadResponse.data
                
                // 验证返回的文件URL
                if (resourceUrl && typeof resourceUrl === 'string') {
                  if (!resourceUrl.startsWith('http') || !resourceUrl.includes('/')) {
                    console.error('服务器返回了无效的URL格式:', resourceUrl)
                    throw new Error(`服务器返回了无效的URL: ${resourceUrl}`)
                  }
                }
              }
              
              // 创建作业对象
              const assignment = {
                courseId: courseId,
                classId: classId,
                teacherId: teacherId,
            title: this.homeworkForm.title,
                description: this.homeworkForm.description,
            deadline: this.homeworkForm.deadline,
                resourceUrl: resourceUrl
              }
              
              // 发布作业
              return addAssignment(assignment)
            })
            .then(response => {
              if (response.code === 200) {
                this.$message.success('作业发布成功')
                this.homeworkDialog.visible = false
                // 重新加载作业列表
                this.loadHomeworkList()
              } else {
                this.$message.error(response.message || '作业发布失败')
              }
            })
            .catch(error => {
              console.error('发布作业错误:', error)
              this.$message.error(error.message || '发布作业异常，请稍后重试')
          })
        }
      })
    },
    handleGradeHomework(homework) {
      this.gradeDialog.currentHomework = homework;
      this.gradeDialog.visible = true;
      this.submissionList = [];
      this.filteredSubmissionList = [];
      this.gradeFilter = 'all';
      this.submissionsLoading = true;
      
      // 获取作业的提交列表
      getSubmissionsByAssignmentId(homework.id)
        .then(response => {
          if (response.code === 200) {
            // 先获取作业的详细信息，包括截止日期
            getAssignmentDetail(homework.id)
              .then(detailResponse => {
                let deadline = null;
                if (detailResponse.code === 200 && detailResponse.data) {
                  deadline = detailResponse.data.deadline;
                  // 更新当前作业对象的截止日期
                  if (this.gradeDialog.currentHomework) {
                    this.gradeDialog.currentHomework.deadline = deadline;
                  }
                }
                
                // 处理提交列表数据，只保留每个学生的最新提交
                this.processSubmissions(response.data, homework);
              })
              .catch(error => {
                console.error('获取作业详情失败:', error);
                // 尽管获取详情失败，仍然处理提交列表
                this.processSubmissions(response.data, homework);
              })
              .finally(() => {
                this.submissionsLoading = false;
              });
          } else {
            this.$message.error(response.msg || '获取提交列表失败');
            this.submissionsLoading = false;
          }
        })
        .catch(error => {
          console.error('获取提交列表错误:', error);
          this.$message.error('获取提交列表异常，请稍后重试');
          this.submissionsLoading = false;
        });
    },
    
    // 辅助方法：处理提交记录
    processSubmissions(submissions, homework) {
      if (!submissions || submissions.length === 0) {
        // 如果没有提交记录，显示提示信息
        this.$message.info('该作业暂无学生提交记录');
        
        // 将提交数量设为0
        const index = this.homeworkList.findIndex(h => h.id === homework.id);
        if (index !== -1) {
          this.homeworkList[index].submittedCount = 0;
          if (this.gradeDialog.currentHomework) {
            this.gradeDialog.currentHomework.submittedCount = 0;
          }
        }
        return;
      }
      
      console.log('获取到的提交记录总数量:', submissions.length);
      
      // 获取截止日期
      const deadline = this.gradeDialog.currentHomework ? this.gradeDialog.currentHomework.deadline : null;
      
      // 按学生ID对提交记录进行分组
      const submissionsByStudent = {};
      
      // 遍历所有提交记录
      submissions.forEach(submission => {
        if (!submission.studentId) {
          console.error('提交记录缺少学生ID:', submission);
          return; // 跳过无效的提交记录
        }
        
        const studentId = submission.studentId;
        const submitTime = new Date(submission.createTime || submission.submitTime);
        
        // 如果是该学生的第一条记录，或者比之前的记录更新，则替换
        if (!submissionsByStudent[studentId] || 
            submitTime > new Date(submissionsByStudent[studentId].createTime || submissionsByStudent[studentId].submitTime)) {
          submissionsByStudent[studentId] = submission;
        }
      });
      
      // 将分组后的最新提交转换为数组
      const latestSubmissions = Object.values(submissionsByStudent);
      console.log('过滤后只保留最新提交的记录数量:', latestSubmissions.length);
      
      // 转换提交记录为界面显示格式
      this.submissionList = latestSubmissions.map(submission => {
        let studentName = '未知学生';
        
        // 尝试从不同来源获取学生姓名
        if (submission.student && submission.student.name) {
          studentName = submission.student.name;
        } else if (submission.s_name) {
          studentName = submission.s_name;
        } else if (submission.studentName) {
          studentName = submission.studentName;
        }
        
        // 判断是否是超期提交
        let isOverdue = false;
        if (deadline && (submission.createTime || submission.submitTime)) {
          const deadlineDate = new Date(deadline);
          const submitDate = new Date(submission.createTime || submission.submitTime);
          isOverdue = submitDate > deadlineDate;
        } else if (submission.isOverdue) {
          // 如果后端已经标记了超期提交
          isOverdue = true;
        }
        
        return {
          submissionId: submission.submissionId,
          studentId: submission.studentId,
          studentName: studentName,
          submitTime: this.formatDate(submission.createTime || submission.submitTime),
          fileName: this.getFileNameFromUrl(submission.fileUrl) || '无文件',
          fileUrl: submission.fileUrl,
          score: submission.score || 0,
          comment: submission.feedback || '',
          isOverdue: isOverdue
        };
      });
      
      // 初始化过滤后的列表
      this.filterSubmissions();
      
      // 更新作业列表中当前作业的提交数量
      const submittedCount = this.submissionList.length;
      const index = this.homeworkList.findIndex(h => h.id === homework.id);
      if (index !== -1) {
        console.log(`更新作业[${homework.title}]的提交数量：从 ${this.homeworkList[index].submittedCount} 更新为 ${submittedCount}`);
        this.homeworkList[index].submittedCount = submittedCount;
        
        // 更新当前打开的作业对象
        if (this.gradeDialog.currentHomework) {
          this.gradeDialog.currentHomework.submittedCount = submittedCount;
        }
      }
    },
    viewHomeworkDetail(homework) {
      this.currentHomework = homework;
      this.homeworkDetailDialog.currentHomework = homework;
      this.homeworkDetailDialog.visible = true;
    },
    handleDeleteHomework(homework) {
      const hasAttachment = homework.resourceUrl && homework.resourceUrl.trim() !== '';
      let confirmMessage = '确认删除该作业吗？删除后无法恢复。';
      
      if (hasAttachment) {
        confirmMessage += '与该作业关联的附件文件也将被删除。';
      }
      
      this.$confirm(confirmMessage, '提示', {
        type: 'warning'
      }).then(() => {
        // 调用删除作业接口
        deleteAssignment(homework.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              // 从列表中移除该作业
        const index = this.homeworkList.findIndex(h => h.id === homework.id)
        if (index !== -1) {
          this.homeworkList.splice(index, 1)
        }
              // 更新统计数据
              this.course.homeworkCount = this.homeworkList.length
            } else {
              this.$message.error(response.msg || '删除作业失败')
            }
          })
          .catch(error => {
            console.error('删除作业错误:', error)
            this.$message.error('删除作业异常，请稍后重试')
          })
      }).catch(() => {
        // 用户取消删除，不做任何操作
      })
    },
    downloadSubmission(submission) {
      if (!submission.fileUrl) {
        this.$message.warning('该提交没有附件')
        return
      }
      
      // 使用相同的直接链接方式下载
      window.open(submission.fileUrl, '_blank')
    },
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return '';
      
      try {
        // 尝试从URL查询参数中提取BASE64编码的原始文件名
        const urlObj = new URL(url);
        const encodedName = urlObj.searchParams.get('name');
        
        if (encodedName) {
          // 解码BASE64编码的原始文件名
          try {
            // 使用window.atob解码BASE64字符串
            const base64Decoded = atob(encodedName);
            
            // 将UTF-8编码的字节转换为JavaScript字符串
            // 这种方法可以正确处理中文等非ASCII字符
            const bytes = new Uint8Array(base64Decoded.length);
            for (let i = 0; i < base64Decoded.length; i++) {
              bytes[i] = base64Decoded.charCodeAt(i);
            }
            const decodedName = new TextDecoder('utf-8').decode(bytes);
            
            console.log('从URL查询参数中解码的原始文件名:', decodedName);
            return decodedName;
          } catch (e) {
            console.error('BASE64解码失败:', e);
          }
        }
        
        // 如果没有查询参数或解码失败，则从路径中提取文件名
        const pathParts = urlObj.pathname.split('/');
        const fileName = pathParts[pathParts.length - 1];
        console.log('从URL路径中提取的文件名:', fileName);
        return fileName;
      } catch (error) {
        // 如果URL解析失败，使用简单方法提取
        console.error('URL解析失败:', error);
        const parts = url.split('/');
        const lastPart = parts[parts.length - 1].split('?')[0]; // 移除查询参数
        return lastPart;
      }
    },
    
    // 从文件名中获取可读的文件名（可能是UUID）
    getOriginalFileName(url) {
      if (!url) return '';
      
      try {
        // 格式1: 从name参数中获取Base64编码的原始文件名（阿里云OSS服务实现）
        const urlObj = new URL(url);
        const encodedName = urlObj.searchParams.get('name');
        
        if (encodedName) {
          // 解码BASE64编码的原始文件名
          try {
            // 使用window.atob解码BASE64字符串
            const base64Decoded = atob(encodedName);
            
            // 将UTF-8编码的字节转换为JavaScript字符串
            // 这种方法可以正确处理中文等非ASCII字符
            const bytes = new Uint8Array(base64Decoded.length);
            for (let i = 0; i < base64Decoded.length; i++) {
              bytes[i] = base64Decoded.charCodeAt(i);
            }
            const decodedName = new TextDecoder('utf-8').decode(bytes);
            
            console.log('从URL查询参数中解码的原始文件名:', decodedName);
            return decodedName;
          } catch (e) {
            console.error('BASE64解码失败:', e);
          }
        }
        
        // 格式2: 从其他可能的查询参数中获取原始文件名
        const filename = urlObj.searchParams.get('filename');
        if (filename) {
          return decodeURIComponent(filename);
        }
        
        // 格式3: 从路径中提取文件名
        const pathParts = urlObj.pathname.split('/');
        let fileName = pathParts[pathParts.length - 1];
        
        // 如果文件名包含查询参数，去除它们
        if (fileName.includes('?')) {
          fileName = fileName.split('?')[0];
        }
        
        // 尝试从文件名中提取原始名称
        // 格式: 原始名_时间戳.扩展名 或 时间戳_原始名.扩展名
        const filenameMatch = fileName.match(/(.+)_\d+\.(\w+)$/) || fileName.match(/\d+_(.+)\.(\w+)$/);
        if (filenameMatch) {
          const extractedName = filenameMatch[1] + '.' + filenameMatch[2];
          console.log('从路径中提取的原始文件名:', extractedName);
          return extractedName;
        }
        
        return fileName || '下载文件';
      } catch (error) {
        console.error('解析文件名出错:', error);
        return '下载文件';
      }
    },
    handleAddAnnouncement() {
      this.announcementDialog.title = '发布公告'
      // 获取教师ID
      const teacherId = this.getCurrentTeacherId()
      
      this.announcementForm = {
        title: '',
        content: '',
        courseId: this.$route.params.id,
        classId: parseInt(this.$route.query.classId),
        teacherId: teacherId
      }
      
      // 检查必要参数
      if (!this.announcementForm.courseId) {
        this.$message.error('缺少课程ID')
        return
      }
      
      if (!this.announcementForm.classId) {
        this.$message.error('缺少班级ID')
        return
      }
      
      if (!this.announcementForm.teacherId) {
        this.$message.error('未能获取教师ID，请重新登录')
        return
      }
      
      this.announcementDialog.visible = true
    },
    editAnnouncement(announcement) {
      this.announcementDialog.title = '编辑公告'
      // 获取教师ID
      const teacherId = this.getCurrentTeacherId()
      
      // 确保编辑时保留原有的教师ID
      this.announcementForm = {
        ...announcement,
        announcementId: announcement.announcementId,
        teacherId: announcement.teacherId || teacherId // 优先使用原有的teacherId
      }
      
      // 检查必要参数
      if (!this.announcementForm.courseId) {
        this.$message.error('缺少课程ID')
        return
      }
      
      if (!this.announcementForm.classId) {
        this.$message.error('缺少班级ID')
        return
      }
      
      if (!this.announcementForm.teacherId) {
        this.$message.error('未能获取教师ID，请重新登录')
        return
      }
      
      this.announcementDialog.visible = true
    },
    deleteAnnouncement(announcement) {
      this.$confirm('确认删除该公告吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteCourseAnnouncement(announcement.announcementId)
          .then(response => {
            if (response.code === 200) {
        this.$message.success('删除成功')
              // 重新加载公告列表
              this.loadAnnouncements()
            } else {
              this.$message.error(response.msg || '删除公告失败')
            }
          })
          .catch(error => {
            console.error('删除公告错误:', error)
            this.$message.error('删除公告异常，请稍后重试')
          })
      }).catch(() => {})
    },
    submitAnnouncement() {
      this.$refs.announcementForm.validate(valid => {
        if (valid) {
          // 额外检查必要参数是否存在
          if (!this.announcementForm.courseId || !this.announcementForm.classId || !this.announcementForm.teacherId) {
            this.$message.error('缺少必要参数，请重新填写')
            return
          }
          
          const isEdit = !!this.announcementForm.announcementId
          
          if (isEdit) {
            // 编辑现有公告
            const announcementId = this.announcementForm.announcementId
            updateCourseAnnouncement(announcementId, this.announcementForm)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('更新公告成功')
                  // 重新加载公告列表
                  this.loadAnnouncements()
                  this.announcementDialog.visible = false
                } else {
                  this.$message.error(response.msg || '更新公告失败')
                }
              })
              .catch(error => {
                console.error('更新公告错误:', error)
                this.$message.error('更新公告异常，请稍后重试')
              })
          } else {
            // 添加新公告
            addCourseAnnouncement(this.announcementForm)
              .then(response => {
                if (response.code === 200) {
                  this.$message.success('发布公告成功')
                  // 重新加载公告列表
                  this.loadAnnouncements()
                  this.announcementDialog.visible = false
                } else {
                  this.$message.error(response.msg || '发布公告失败')
                }
              })
              .catch(error => {
                console.error('发布公告错误:', error)
                this.$message.error('发布公告异常，请稍后重试')
              })
          }
        }
      })
    },
    // 加载课程作业列表
    loadHomeworkList() {
      const courseId = this.$route.params.id
      const classId = this.$route.query.classId
      
      if (!courseId || !classId) {
        this.$message.error('缺少课程ID或班级ID参数')
        return
      }
      
      this.homeworkLoading = true
      getCourseAssignments(courseId, classId)
        .then(response => {
          if (response.code === 200) {
            console.log('作业列表原始数据:', response.data)
            
            // 处理作业数据
            this.homeworkList = response.data.map(item => {
              // 确保submittedCount是数值类型
              let submittedCount = 0
              if (item.submittedCount !== undefined && item.submittedCount !== null) {
                submittedCount = parseInt(item.submittedCount) || 0
              }
              
              console.log(`作业[${item.title}]的提交数量:`, item.submittedCount, '类型:', typeof item.submittedCount, '转换后:', submittedCount)
              
              return {
                id: item.assignmentId,
                title: item.title,
                deadline: this.formatDate(item.deadline),
                description: item.description,
                resourceUrl: item.resourceUrl,
                submittedCount: submittedCount
              }
            })
            
            // 更新统计数据
            this.course.homeworkCount = this.homeworkList.length
            this.course.pendingHomework = this.homeworkList.reduce((total, homework) => {
              // 未批改作业数量 = 提交数量 - 已批改数量
              return total + (homework.submittedCount - (homework.gradedCount || 0))
            }, 0)
            
            console.log('处理后的作业列表:', this.homeworkList)
          } else {
            this.$message.error(response.msg || '获取作业列表失败')
          }
        })
        .catch(error => {
          console.error('获取作业列表错误:', error)
          this.$message.error('获取作业列表异常，请稍后重试')
        })
        .finally(() => {
          this.homeworkLoading = false
        })
    },
    // 加载课程公告
    loadAnnouncements() {
      const courseId = this.$route.params.id
      const classId = this.$route.query.classId
      
      if (!courseId || !classId) {
        this.$message.error('缺少课程ID或班级ID参数')
        return
      }
      
      this.announcementsLoading = true
      getAnnouncementsByCourseAndClass(courseId, classId)
        .then(response => {
          if (response.code === 200) {
            this.announcements = response.data
          } else {
            this.$message.error(response.msg || '获取课程公告失败')
          }
        })
        .catch(error => {
          console.error('获取课程公告错误:', error)
          this.$message.error('获取课程公告异常，请稍后重试')
        })
        .finally(() => {
          this.announcementsLoading = false
        })
    },
    downloadHomeworkResource(url) {
      if (!url) {
        this.$message.warning('附件URL无效')
        return
      }
      
      this.downloadFile(url)
    },
    // 根据扩展名获取文件类型
    getFileTypeByExtension(extension) {
      const lowerExt = extension.toLowerCase()
      const typeMap = {
        'pdf': 'PDF',
        'doc': '文档',
        'docx': '文档',
        'xls': '表格',
        'xlsx': '表格',
        'ppt': '演示',
        'pptx': '演示', 
        'txt': '文本',
        'zip': '压缩',
        'rar': '压缩',
        'jpg': '图片',
        'jpeg': '图片',
        'png': '图片',
        'gif': '图片'
      }
      
      return typeMap[lowerExt] ? typeMap[lowerExt] : ''
    },
    // 下载文件
    downloadFile(url) {
      if (!url) {
        this.$message.warning('文件链接不存在')
        return
      }
      
      // 从URL获取原始文件名
      const originalFileName = this.getOriginalFileName(url)
      console.log('下载使用的文件名:', originalFileName)
      
      // 直接使用a标签的download属性实现下载
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', originalFileName)
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('文件下载已开始')
    },

    submitGrades() {
      if (this.submissionList.length === 0) {
        this.$message.warning('没有可批改的作业提交记录')
        this.gradeDialog.visible = false
        return
      }
      
      // 验证成绩是否合法
      const invalidScores = this.submissionList.filter(
        submission => submission.score < 0 || submission.score > 100
      )
      
      if (invalidScores.length > 0) {
        this.$message.error('成绩必须在0-100之间')
        return
      }
      
      // 检查是否有未评分的提交
      const ungradedSubmissions = this.submissionList.filter(
        submission => !submission.score || submission.score === 0
      )
      
      // 检查是否有未填写评语的提交
      const noCommentSubmissions = this.submissionList.filter(
        submission => submission.score > 0 && (!submission.comment || submission.comment.trim() === '')
      )
      
      // 设置确认提示信息
      let confirmMessage = '确定要保存所有批改结果吗？'
      let confirmType = 'info'
      
      if (ungradedSubmissions.length > 0) {
        confirmMessage = `有 ${ungradedSubmissions.length} 份作业未评分或评为0分，确定要保存吗？`
        confirmType = 'warning'
      } else if (noCommentSubmissions.length > 0) {
        confirmMessage = `有 ${noCommentSubmissions.length} 份作业未填写评语，确定要保存吗？`
        confirmType = 'warning'
      }
      
      // 显示确认对话框
      this.$confirm(confirmMessage, '批量保存评分', {
        confirmButtonText: '确定保存',
        cancelButtonText: '返回编辑',
        type: confirmType,
        closeOnClickModal: false
      }).then(() => {
      const teacherId = this.getCurrentTeacherId()
      if (!teacherId) {
        this.$message.error('未能获取教师ID，请重新登录')
        return
      }
      
      // 显示加载
      const loading = this.$loading({
        lock: true,
        text: '正在保存评分...',
        spinner: 'el-icon-loading'
      })
      
      // 批量保存评分
      const promises = this.submissionList.map(submission => 
        gradeSubmission(
          submission.submissionId,
          submission.score,
          submission.comment || '',
          teacherId
        )
      )
      
      Promise.all(promises)
        .then(() => {
          loading.close()
          this.$message.success('评分保存成功')
          this.gradeDialog.visible = false
          
          // 重新加载作业列表以更新统计数据
          this.loadHomeworkList()
        })
        .catch(error => {
          loading.close()
          console.error('保存评分错误:', error)
          this.$message.error('保存评分异常，请稍后重试')
          })
      }).catch(() => {
        // 用户取消操作
        })
    },
    
    // 日期格式化
    formatDate(dateString) {
      if (!dateString) return ''
      
      try {
        const date = new Date(dateString)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
      } catch (error) {
        return dateString
      }
    },
    // 根据过滤条件筛选提交列表
    filterSubmissions() {
      if (this.gradeFilter === 'all') {
        this.filteredSubmissionList = [...this.submissionList];
      } else if (this.gradeFilter === 'graded') {
        this.filteredSubmissionList = this.submissionList.filter(item => item.score > 0);
      } else if (this.gradeFilter === 'ungraded') {
        this.filteredSubmissionList = this.submissionList.filter(item => !item.score || item.score === 0);
      } else if (this.gradeFilter === 'overdue') {
        this.filteredSubmissionList = this.submissionList.filter(item => item.isOverdue);
      }
    },
    
    // 查看提交详情
    viewSubmissionDetail(row) {
      this.currentSubmission = JSON.parse(JSON.stringify(row)); // 深拷贝，避免直接修改原始数据
      this.submissionDetailDialog.visible = true;
    },
    
    // 保存当前查看的提交记录
    saveCurrentSubmission() {
      if (!this.currentSubmission) {
        this.$message.warning('提交记录不存在');
        return;
      }
      
      // 检查是否填写了分数和评语
      let confirmMessage = '确定要保存批改结果吗？';
      let confirmType = 'info';
      
      if (this.currentSubmission.score === null || this.currentSubmission.score === undefined || this.currentSubmission.score === 0) {
        confirmMessage = '您尚未填写分数或设置为0分，确定要保存批改吗？';
        confirmType = 'warning';
      } else if (!this.currentSubmission.comment) {
        confirmMessage = '您尚未填写评语，确定要保存批改吗？';
        confirmType = 'warning';
      }
      
      // 显示确认对话框
      this.$confirm(confirmMessage, '保存批改', {
        confirmButtonText: '确定保存',
        cancelButtonText: '返回编辑',
        type: confirmType,
        closeOnClickModal: false
      }).then(() => {
      // 更新原始提交列表中的数据
      const index = this.submissionList.findIndex(
        item => item.submissionId === this.currentSubmission.submissionId
      );
      
      if (index !== -1) {
        this.submissionList[index].score = this.currentSubmission.score;
        this.submissionList[index].comment = this.currentSubmission.comment;
        this.filterSubmissions(); // 重新过滤列表
        this.$message.success('已更新评分信息');
        this.submissionDetailDialog.visible = false;
      } else {
        this.$message.error('未找到对应的提交记录');
      }
      }).catch(() => {
        // 用户取消，继续编辑
      });
    },
    isOverdue(deadline, submitTime) {
      if (!deadline || !submitTime) return false;
      
      const deadlineDate = new Date(deadline);
      const submitDate = new Date(submitTime);
      
      const timeDiff = submitDate - deadlineDate;
      const hoursDiff = Math.abs(timeDiff) / (1000 * 3600);
      
      return hoursDiff > 24;
    },
    // 获取测试状态对应的样式类型
    getQuizStatusType(status) {
      switch (Number(status)) {
        case 0: return 'info'    // 未开始
        case 1: return 'success' // 进行中
        case 2: return 'warning' // 已结束
        default: return 'info'
      }
    },
    
    // 获取测试状态对应的文字描述
    getQuizStatusText(status) {
      switch (Number(status)) {
        case 0: return '未开始'
        case 1: return '进行中'
        case 2: return '已结束'
        default: return '未知'
      }
    },
    
    // 加载随堂测试列表
    loadQuizList() {
      const courseId = this.$route.params.id
      const classId = this.$route.query.classId
      
      if (!courseId || !classId) {
        this.$message.error('缺少课程ID或班级ID参数')
        return
      }
      
      this.quizLoading = true
      getCourseQuizList(courseId, classId)
        .then(response => {
          if (response.code === 200) {
            this.quizList = response.data || []
          } else {
            this.$message.error(response.msg || '获取随堂测试列表失败')
          }
        })
        .catch(error => {
          console.error('获取随堂测试列表错误:', error)
          this.$message.error('获取随堂测试列表异常，请稍后重试')
        })
        .finally(() => {
          this.quizLoading = false
        })
    },
    
    // 创建随堂测试
    handleCreateQuiz() {
      // 重置表单
      this.quizDialog.title = '创建随堂测试'
      this.quizForm = {
        title: '',
        description: '',
        questions: []
      }
      this.currentQuestion = {
        content: '',
        options: ['', '', '', ''],
        answer: 0
      }
      
      // 显示创建对话框
      this.quizDialog.visible = true
    },
    
    // 添加题目到表单
    addQuestion() {
      // 验证当前题目
      if (!this.currentQuestion.content.trim()) {
        this.$message.warning('请输入题目内容')
        return
      }
      
      // 检查选项是否完整
      for (let i = 0; i < this.currentQuestion.options.length; i++) {
        if (!this.currentQuestion.options[i].trim()) {
          this.$message.warning(`请输入选项${['A', 'B', 'C', 'D'][i]}的内容`)
          return
        }
      }
      
      // 深拷贝当前题目，避免引用问题
      const newQuestion = {
        content: this.currentQuestion.content,
        options: [...this.currentQuestion.options],
        answer: this.currentQuestion.answer
      }
      
      // 添加到题目列表
      this.quizForm.questions.push(newQuestion)
      
      // 重置当前题目表单
      this.currentQuestion = {
        content: '',
        options: ['', '', '', ''],
        answer: 0
      }
      
      this.$message.success('题目添加成功')
    },
    
    // 提交创建测试表单
    submitQuiz() {
      // 简化验证过程，只验证标题
      if (!this.quizForm.title.trim()) {
        this.$message.warning('请输入测试标题')
        return
      }
      
      // 检查题目列表
      if (this.quizForm.questions.length === 0) {
        this.$message.warning('请至少添加一道题目')
        return
      }
      
      const courseId = this.$route.params.id
      const classId = parseInt(this.$route.query.classId)
      const teacherId = this.getCurrentTeacherId()
      
      if (!courseId || !classId || !teacherId) {
        this.$message.error('缺少必要参数')
        return
      }
      
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '创建测试中...',
        spinner: 'el-icon-loading'
      })
      
      // 准备要发送的数据
      const quizData = {
        courseId,
        classId,
        teacherId,
        title: this.quizForm.title,
        description: this.quizForm.description || ''
      }
      
      // 将题目转换为服务器期望的格式
      const formattedQuestions = this.quizForm.questions.map(q => ({
        quizId: null, // 会由后端设置
        questionText: q.content,
        options: JSON.stringify(q.options), // 直接以JSON格式发送选项数组
        correctAnswer: String(q.answer), // 确保是字符串
        score: 10 // 设置默认分数
      }))
      
      // 调用创建测试API
      createQuiz({
        ...quizData,
        questions: JSON.stringify(formattedQuestions)
      })
        .then(response => {
          loading.close()
          if (response.code === 200) {
            this.$message.success('随堂测试创建成功')
            this.quizDialog.visible = false
            // 重新加载测试列表
            this.loadQuizList()
          } else {
            this.$message.error(response.msg || '创建随堂测试失败')
          }
        })
        .catch(error => {
          loading.close()
          console.error('创建随堂测试错误:', error)
          this.$message.error('创建测试失败：' + (error.message || '未知错误'))
        })
    },
    
    // 从表单中删除题目
    removeQuestion(index) {
      this.quizForm.questions.splice(index, 1)
      this.$message.success('题目删除成功')
    },
    
    // 修改测试状态（开始/结束）
    handleQuizStatus(quiz) {
      const statusAction = quiz.status === 0 ? '开始' : '结束'
      
      this.$confirm(`确定要${statusAction}此测试吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const apiMethod = quiz.status === 0 ? startQuiz : endQuiz
        
        apiMethod(quiz.quizId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success(`测试已${statusAction}`)
              // 更新状态
              const index = this.quizList.findIndex(item => item.quizId === quiz.quizId)
              if (index !== -1) {
                this.quizList[index].status = quiz.status === 0 ? 1 : 2
              }
            } else {
              this.$message.error(response.msg || `${statusAction}测试失败`)
            }
          })
          .catch(error => {
            console.error(`${statusAction}测试错误:`, error)
            this.$message.error(`${statusAction}测试异常，请稍后重试`)
          })
      }).catch(() => {
        // 用户取消操作
      })
    },
    
    // 查看测试详情
    handleViewQuizDetail(quiz) {
      // 跳转到测试详情页面
      this.$router.push({
        name: 'TeacherQuizDetail',
        params: { quizId: quiz.quizId }
      })
    },
    
    // 删除测试
    handleDeleteQuiz(quiz) {
      // 正在进行中的测试不能删除
      if (quiz.status === 1) {
        this.$message.warning('进行中的测试不能删除，请先结束测试')
        return
      }
      
      this.$confirm('确定要删除此测试吗？删除后无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuiz(quiz.quizId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              // 从列表中移除该测试
              const index = this.quizList.findIndex(item => item.quizId === quiz.quizId)
              if (index !== -1) {
                this.quizList.splice(index, 1)
              }
            } else {
              this.$message.error(response.msg || '删除测试失败')
            }
          })
          .catch(error => {
            console.error('删除测试错误:', error)
            this.$message.error('删除测试异常，请稍后重试')
          })
      }).catch(() => {
        // 用户取消删除，不做任何操作
      })
    }
  }
}
</script>

<style scoped>
.course-detail {
  padding: 20px;
}

.course-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.course-info h2 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.course-info p {
  margin: 5px 0;
  color: #606266;
}

.course-stats {
  min-width: 300px;
}

.stat-card {
  background-color: white;
  padding: 15px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.nav-section {
  margin-bottom: 20px;
}

.content-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.info-content {
  max-width: 600px;
}

.grade-content {
  margin-bottom: 20px;
}

.homework-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
}

.file-link {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
  display: inline-flex;
  align-items: center;
}

.file-link:hover {
  color: #66b1ff;
}

.file-link::before {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  background-image: url('');
  background-size: contain;
  margin-right: 4px;
}

/* 新增样式 */
.homework-header {
  padding: 0 10px 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.homework-header h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #409EFF;
}

.info-item {
  margin-bottom: 8px;
  line-height: 1.5;
}

.info-label {
  font-weight: bold;
  color: #606266;
  margin-right: 5px;
}

.description-text {
  margin: 5px 0;
  white-space: pre-line;
  color: #606266;
}

.grade-toolbar {
  margin-bottom: 15px;
  padding: 0 5px;
}

.text-right {
  text-align: right;
}

.no-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 10px;
}

.no-data p {
  font-size: 14px;
}

.submission-detail {
  padding: 10px;
}

/* 表格行鼠标悬停效果 */
.el-table .el-table__row:hover {
  cursor: pointer;
  background-color: #f0f9ff !important;
}

.action-name {
  font-size: 14px;
  color: #606266;
}

/* 学生详情对话框样式 */
.profile-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.profile-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  border-radius: 50%;
  margin-bottom: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 原有样式 */
.student-info-item {
  margin-bottom: 12px;
  line-height: 22px;
}

.student-info-item .label {
  color: #606266;
  margin-right: 10px;
  font-weight: bold;
}

.student-info-item .value {
  color: #303133;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-item .stat-title {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.stat-item .stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-top: 10px;
}

.box-card {
  margin-bottom: 20px;
  border-radius: 4px;
}

.no-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 10px;
}

.no-data p {
  font-size: 16px;
}

.quiz-content {
  margin-top: 20px;
}

.quiz-table {
  width: 100%;
}

.quiz-table .el-table__row:hover {
  background-color: #f0f9ff !important;
}

.quiz-status {
  font-size: 14px;
  color: #606266;
}

.quiz-status .el-tag {
  margin-right: 10px;
}

.quiz-actions {
  text-align: right;
}

.quiz-actions .el-button {
  margin-left: 10px;
}

/* 随堂测试题目样式 */
.question-item {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 5px;
  margin-bottom: 10px;
}

.question-content {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #ebeef5;
}

.question-options {
  margin-bottom: 15px;
}

.question-options p {
  margin: 8px 0;
  padding: 5px 10px;
  border-radius: 4px;
}

.option-label {
  font-weight: bold;
  margin-right: 5px;
}

.correct-option {
  background-color: #f0f9eb;
  color: #67c23a;
  border-left: 3px solid #67c23a;
}

.question-actions {
  text-align: right;
}

/* 新增题目表单样式 */
.new-question-form {
  background-color: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 20px;
}

.new-question-form .el-form-item:last-child {
  margin-bottom: 0;
}

.new-question-form .el-button {
  margin-top: 10px;
}

/* 自定义表单样式 */
.quiz-form {
  padding: 10px;
}

.form-item {
  margin-bottom: 22px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #606266;
  line-height: 1;
  padding: 0 0 10px;
  font-weight: normal;
}

.form-label.required:before {
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}
</style> 